package com.instpower.things.entity;

import com.instpower.things.helper.Utils;
import com.instpower.things.transport.DataBuffer;

/**
 * @ClassName 固件信息
 * @Author: hellmash@gmail.com
 * @Date: 2020/5/2
 * @Version: 1.0.0
 * @Description: TODO
 */
public class FirmwareInfo {

    public enum Protocol{
        FTP, HTTP, HTTPS;
    }

    private Protocol protocol;

    /**
     * IP地址
     */
    private String ipAddress;

    /**
     * 端口
     */
    private short port;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * URL长度
     */
    private int length;

    /**
     * url地址,不包含ip地址
     */
    private String url;

    /**
     * 文件长度
     */
    private int fileLenght;

    /**
     * 总校验和
     */
    private int checkSum;

    /**
     * encode对象
     * @return
     */
    public DataBuffer encode() {
        DataBuffer buffer = new DataBuffer();
        if(protocol == Protocol.FTP)
            buffer.writeByte(0x00);
        else if(protocol == Protocol.HTTPS)
            buffer.writeByte(0x02);
        else
            buffer.writeByte(0x01);
        DataBuffer ipBuffer = Utils.parseIp(ipAddress);
        if(ipBuffer == null)
            return buffer;

        buffer.writeDataBuffer(ipBuffer);

        buffer.writeShort(port);

        buffer.writeStringFixed(username, 10, (byte)0x00);

        buffer.writeStringFixed(password, 10, (byte)0x00);

        this.length = url.length() + 1;
        buffer.writeByte(length);

        buffer.writeStringFixed(url, length, (byte)0x00);

        buffer.writeInt(fileLenght);

        buffer.writeInt(checkSum);

        return buffer;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public void setPort(short port) {
        this.port = port;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setFileLenght(int fileLenght) {
        this.fileLenght = fileLenght;
    }

    public void setCheckSum(int checkSum) {
        this.checkSum = checkSum;
    }
}
